package pe.com.tma.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import pe.com.tma.dao.AuthenticationDAO;
import pe.com.tma.model.Perfil;
import pe.com.tma.model.Usuario;

public class JPAAuthenticationDAO implements AuthenticationDAO {

	@Resource(name = "authenticationManager")
	private AuthenticationManager authenticationManager; // specific for Spring Security

	@Override
	public boolean login(String username, String password) {
		try {
			Authentication authenticate = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(
							username, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(
						authenticate);				
				return true;
			}
		} catch (AuthenticationException e) {			
		}
		return false;
	}

	@Override
	public void logout() {
		SecurityContextHolder.getContext().setAuthentication(null);
		//currentUser.unauthenticate();
	}

	@Override
	public List<Usuario> buscarUsuarioPorCodigo(String username) {
		List<Usuario> rst = new ArrayList<Usuario>();
		
		Usuario user = new Usuario();
		//user.setUsername("admin");
		//user.setPassword("admin");
		//user.setAccountNonExpired(true);
		//user.setAccountNonLocked(true);
		//user.setCredentialsNonExpired(true);
		//user.setEnabled(true);
		rst.add(user);
		
		return rst;
	}

	@Override
	public List<GrantedAuthority> buscarPerfilesDeUsuarioPorCodigo(String username) {
		// TODO Auto-generated method stub
		List<GrantedAuthority> rst = new ArrayList<GrantedAuthority>();
		Perfil perfil = new Perfil();
		perfil.setNombrePerfil("ROLE_ADMIN");
		rst.add(perfil);
		return rst;
	}

}
